<template>
  <div id='bdmap' style="height: 100%;"></div>
</template>

<script>
/* eslint-disable no-undef */

import jsonp from 'jsonp'
// const BMap = window.BMap
export default {
  props: {
    mode: null
  },
  data () {
    return {
      _map: null
    }
  },
  watch: {
    $bdmap (val) {
      console.log('watch bdmap', val)
    }
  },
  mounted () {
    // alert('loading script')
    this.loadScript(this.$bdmap.ak).then(() => {
      // alert('promise map loaded')
      this.init()
    })
  },
  methods: {
    init () {
      this.createMap()
      this.addControls()
      this.setMapEvent()
      if (this.mode === 'showAll') {
        this.showPOI('113.088165,22.584459', 10000000)
      } else if (this.mode === 'nearby') {
        this.searchNearby().then((poi) => {
          let point = new window.BMap.Point(poi.location[0], poi.location[1])
          let infoWindow = this.createInfoWindow(poi)
          this._map.openInfoWindow(infoWindow, point)
        })
      }
    },
    loadScript (ak) {
      const loader = new Promise((resolve, reject) => {
        let script

        window._baiduMapLoaded = global._baiduMapLoaded = () => {
          // this.$bdmap.loaded = true
          // alert('callback invoked!')
          // console.log(this.$bdmap)
          document.body.removeChild(script)
          script = null
          resolve()
        }

        if (window.BMap !== undefined && typeof window.BMap === 'object' && typeof window.BMap.Map === 'function') {
          resolve()
        } else {
          script = document.createElement('script')
          script.setAttribute('src', `http://api.map.baidu.com/api?v=2.0&ak=${ak}&callback=_baiduMapLoaded`)
          document.body.appendChild(script)
        }
      })

      return loader
    },
    createMap () {
      this._map = new window.BMap.Map('bdmap')
      this._map.centerAndZoom(new window.BMap.Point(113.088165, 22.584459), 12)
    },
    addControls () {
      let navControl = new window.BMap.NavigationControl({
        anchor: window.BMAP_ANCHOR_TOP_LEFT,
        type: window.BMAP_NAVIGATION_CONTROL_SMALL
      })
      this._map.addControl(navControl)
    },
    setMapEvent () {
      this._map.enableScrollWheelZoom()
      // map.enableKeyboard()
      this._map.enableDragging()
      this._map.enableDoubleClickZoom()
    },
    addMarker (poi, index) {
      let point = new window.BMap.Point(poi.location[0], poi.location[1])
      let marker = new window.BMap.Marker(point)
      this._map.addOverlay(marker)

      let label = new window.BMap.Label(index)
      label.setStyle({
        background: 'none', border: 0, color: '#fff', padding: '3px 6px'
      })
      // label.setOffset()
      marker.setLabel(label)

      let infoWindow = this.createInfoWindow(poi)  // 创建信息窗口对象
      marker.addEventListener('click', (e) => {
        this._map.openInfoWindow(infoWindow, point)
      })
    },

    createInfoWindow (poi) {
      let sContent = ''
      sContent += `<h4 class="weui-media-box__title">${poi.title}</h4>`
      sContent += `<p class="weui-media-box__desc">地址：${poi.address}</p>`
      // sContent += '<a href="#" c>查看详情</a>'

      let opts = {
        // title: poi.title,
        width: window.screen.width - 100,
        offset: new window.BMap.Size(0, -15)
      }
      return new window.BMap.InfoWindow(sContent, opts)
    },

    locateMeH5 () {
      return new Promise((resolve, reject) => {
        // alert('正在定位...')
        navigator.geolocation.getCurrentPosition((pos) => {
          // alert('located!')
          let point = new window.BMap.Point(pos.coords.longitude, pos.coords.latitude)
          let convertor = new window.BMap.Convertor()
          let pointArr = []
          pointArr.push(point)
          convertor.translate(pointArr, 1, 5, (data) => {
            resolve(data)
          })
        }, (err) => { alert(err.message) }, {
          timeout: 10 * 1000
        })
      })
    },

    locateMe () {
      return new Promise((resolve, reject) => {
        baidumap_location.getCurrentPosition((pos) => {
          console.log(JSON.stringify(pos, null, 4))
          // alert('located!')
          let point = new window.BMap.Point(pos.longitude, pos.latitude)
          // let convertor = new window.BMap.Convertor()
          // let pointArr = []
          // pointArr.push(point)
          // convertor.translate(pointArr, 1, 5, (data) => {
            // resolve(data)
          // })
          let result = {
            points: [point]
          }
          resolve(result)
        }, (error) => {
          alert(error.message)
        })
      })
    },

    async searchNearby () {
      let pos = await this.locateMe()
      // console.log(pos)
      let marker = new window.BMap.Marker(pos.points[0])
      let label = new window.BMap.Label('我')
      label.setStyle({
        background: 'none', border: 0, color: '#fff', padding: '3px 3px'
      })
      marker.setLabel(label)
      this._map.addOverlay(marker)

      this._map.setCenter(pos.points[0])

      let location = pos.points[0].lng + ',' + pos.points[0].lat
      return this.showPOI(location, 100000)
    },

    showPOI (location, radius) {
      return new Promise((resolve, reject) => {
        const geoTbId = 167605
        const param = `ak=${this.$bdmap.ak}&geotable_id=${geoTbId}&location=${location}&radius=${radius}&sortby=distance:1&page_size=50&callback`
        jsonp('http://api.map.baidu.com/geosearch/v3/nearby', { param }, (err, data) => {
          if (err) {
            console.error(err.message)
            reject(err)
          } else {
            if (data.size > 0) {
              let poi = data.contents[0]
              let point = new window.BMap.Point(poi.location[0], poi.location[1])
              this._map.centerAndZoom(point, 12)

              data.contents.map((poi, index) => {
                this.addMarker(poi, ++index)
                return
              })

              resolve(poi)
            }
          }
        })
      })
    }
  }
}
</script>
